{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Batch Segmentation for Remote Sensing Imagery with SAM 3\n",
    "\n",
    "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/opengeos/segment-geospatial/blob/main/docs/examples/sam3_batch_segmentation.ipynb)\n",
    "\n",
    "This notebook demonstrates how to do batch segmentation for remote sensing imagery with SAM 3.\n",
    "\n",
    "## Installation\n",
    "\n",
    "First, make sure you have the required dependencies installed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install \"segment-geospatial[samgeo3]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import Libraries\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo import SamGeo3, download_file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download Sample Data\n",
    "\n",
    "Let's download sample satellite images covering the University of California, Berkeley, for testing:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_paths = []\n",
    "for i in range(1, 5):\n",
    "    url = f\"https://huggingface.co/datasets/giswqs/geospatial/resolve/main/uc_berkeley_{i}.tif\"\n",
    "    image_path = download_file(url)\n",
    "    image_paths.append(image_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map()\n",
    "for i, image_path in enumerate(image_paths):\n",
    "    m.add_raster(image_path, layer_name=f\"image_{i + 1}\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Request access to SAM3\n",
    "\n",
    "To use SAM3, you need to request access by filling out this form on Hugging Face: https://huggingface.co/facebook/sam3\n",
    "\n",
    "Once you have access, uncomment the following code block and run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# from huggingface_hub import login\n",
    "# login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialize SAM3\n",
    "\n",
    "When initializing SAM3, you can choose the backend from \"meta\", or \"transformers\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam3 = SamGeo3(backend=\"meta\", device=None, checkpoint_path=None, load_from_HF=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set the image batch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam3.set_image_batch(image_paths)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate masks with text prompt\n",
    "\n",
    "Generate masks for all images with a text prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam3.generate_masks_batch(\"building\", min_size=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Access results for each image\n",
    "for i, result in enumerate(sam3.batch_results):\n",
    "    print(f\"Image {i + 1}: Found {len(result['masks'])} objects\")\n",
    "    # result contains: masks, boxes, scores, image, source"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Show results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualize all annotations in a grid\n",
    "sam3.show_anns_batch(ncols=2, show_bbox=True, show_score=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/0c4f0b4b-4104-4a43-9173-ab76e0d2d71a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Save results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam3.show_anns_batch(output_dir=\"output/annotations/\", prefix=\"ann\", dpi=300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save all masks to disk\n",
    "saved_files = sam3.save_masks_batch(\n",
    "    output_dir=\"output/\", prefix=\"building_mask\", unique=True\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "geo",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
